<?php

namespace app\award;

use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\product\Product;
use app\models\product\ProductAreaList;
use app\models\Queue;
use app\models\SetProductCommission;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserAddress;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\models\UserBalance;
use app\models\UserStore;
use app\models\UserStoreLog;
use app\services\Chain;
use yii\helpers\ArrayHelper;

class Award
{
    protected $user;
    protected $order;
    protected $set;

    protected $items;
    protected $firstProduct;

    // 购买时的等级
    protected $user_level = 0;

    // 给上级领导, 要扣掉的钱
    // [需要减掉平级奖]
    protected $money = 0;

    // 是否处理云仓
    protected $change_store = false;

    // 是否为复购
    protected $isRepeat = false;

    // 上级高级
    protected $r = null;

    // 购买金额
    protected $buyAmount = 0;

    /**
     * Award constructor.
     * @param Order $order          订单模型
     * @param bool $change_store    是否改变云仓数量[包含日志], 重算佣金的时候不改变
     */
    public function __construct(Order $order, $change_store = true)
    {
        $this->change_store = $change_store;

        $this->order = $order;
        $this->user = User::findOne(['id' => $order->user_id]);
        $this->set = SetUserUp::getLastOne();


        // 月奖队列
        $queue = new Queue();
        $queue->order_id = $order->id;
        $queue->save();


        // 不是从云仓提货
        $is_extract = $this->order->is_extract;
        if ($is_extract == 0) {

            $this->items = OrderItem::find()
                ->where(['order_id' => $this->order->id])
                ->all();

            $first_order_item = OrderItem::find()
                ->where(['order_id' => $this->order->id])
                ->orderBy(['id' => SORT_ASC])
                ->limit(1)
                ->one();
            $product_id = $first_order_item->product_id;

            $this->firstProduct = Product::findOne(['id' => $product_id]);

            // 购买时的等级
            $log = $this->order->log;
            if ($log) {
                $log = json_decode($log, true);
                if ($log['user']) {
                    $this->user_level = (int)$log['user']['level'];
                }
            }


            // 报单区
            if (ProductAreaList::checkInArea($product_id, Product::$areaMap['REPORT'])) {

                // 从平台走, 还是上级走
                // 这个一定要先算
                $this->exeBox();


                // 由于从平台走, 不返佣, 所以没有 同级奖 和 差价奖了
                // 05-30 又需要了
                // 平级奖是根据差价奖来返的
                $this->newDiffEqual();

                // 分红
                // $this->profit();

                // 累计业绩奖
                $this->sell();

                // 钱是否给上级领导
                $this->leaderMoney();
            }

            // 复购区
            // 复购从平台走, 有差价奖, 没有同级奖
            if (ProductAreaList::checkInArea($product_id, Product::$areaMap['REPEAT'])) {

                $this->isRepeat = true;

                // 从平台走, 还是上级走
                // 这个一定要先算
                $this->exeBox();

                // 由于从平台走, 不返佣, 所以没有 差价奖了
                // 05-30 又需要了
                // 平级奖是根据差价奖来返的
                $this->newDiffEqual();

                // 经销商推经销商 10%
                $this->repeatSvip1();

                // 区域奖5元, 提货的时候, 也需要返此奖
                $this->area();

                // 分红
                // $this->profit();

                // 累计业绩奖
                $this->sell();

                // 钱是否给上级领导
                $this->leaderMoney();

            }

            // 购物区
            if (ProductAreaList::checkInArea($product_id, Product::$areaMap['GENERAL'])) {
            }
        } else {

            // 从云仓提货
            // if (ProductAreaList::checkInArea($product_id, Product::$areaMap['REPEAT'])) {
            //     // 区域奖5元, 提货的时候, 也需要返此奖
            //     $this->area();
            // }

            // 区域奖5元, 提货的时候, 也需要返此奖
            $this->area();
        }


    }

    // 新差价, 新差价
    private function newDiffEqual()
    {
        if ($this->isRepeat) {
            $level = $this->user_level;
            $ratio = 0.5;
        } else {
            $level = $this->tempLevel();
            $ratio = 0.2;
        }

        $amount = $this->order->total_pay - $this->order->total_freight;


        if (!$this->isRepeat) {

            // 首购 经销商, 区代
            // 都是从平台走货
            if ($level >= UserLevel::$keys['svip1']) {
                // $r = Chain::getReferrerChain($this->user->id, [UserLevel::$keys['svip1'], UserLevel::$keys['svip2']], true);

                $r = Chain::getReferrer($this->user->id, true);

                // if ($r) {
                if ($r && $r->level >= UserLevel::$keys['svip1']) {
                    // $r = $r[0];
                    $commission = 0;

                    // 购买区代
                    if ($level == UserLevel::$keys['svip2'] && $r['level'] == UserLevel::$keys['svip2'] && $amount >= $this->set->svip2_amount) {
                        $commission = $this->set->svip2_same;
                    }

                    // 购买经销商
                    if ($level == UserLevel::$keys['svip1'] && $amount >= $this->set->svip1_amount) {
                        $commission = $this->set->svip1_same;
                    }

                    // var_dump($commission);exit;

                    $this->saveCommission($r['id'], $commission, 55, '推荐', '推荐', 0);

                }
            } else {

                // 其它身份, 差价处理

                // var_dump($this->r);exit;

                // 存在高级
                if ($this->r) {
                    $leader = UserLevel::getKey($this->r->level);
                    // $buy = UserLevel::getKey($this->user_level);

                } else {
                    $leader = UserLevel::getKey($this->getX($this->tempLevel()));
                    // var_dump($leader);exit;
                    // $buy = UserLevel::getKey($this->user_level);
                }

                // var_dump($leader, $this->_diff($leader));exit;

                $diff = $amount - $this->_diff($leader);

                if ($diff > 0) {

                    $same = 0;

                    // 有没有平级
                    $x = Chain::getReferrer($this->user->id, true);
                    if ($x && $x->level == $this->tempLevel()) {


                        $same = $amount * $ratio;
                        $this->saveCommission($x['id'], $same, 2, '同级', '同级', 0);


                    }

                    if ($this->r) {
                        if ($this->order->is_platform) {
                            $this->saveCommission($this->r->id, $diff - $same, 1, '差价', '差价', 0);
                        } else {
                            $this->money += $same;
                        }
                    }

                }

            }


        } else {

            // 复购差价处理

            // 存在高级
            if ($this->r) {
                $leader = UserLevel::getKey($this->r->level);
                // $buy = UserLevel::getKey($this->user_level);

            } else {
                $leader = UserLevel::getKey($this->getX($this->user_level));
                // var_dump($leader);exit;
                // $buy = UserLevel::getKey($this->user_level);
            }

            $diff = $amount - $this->_diff($leader);

            if ($diff > 0) {

                $same = 0;

                // 有没有平级
                $x = Chain::getReferrer($this->user->id, true);
                if ($x && $x->level == $this->user_level) {


                    $same = $diff * $ratio;
                    $this->saveCommission($x['id'], $same, 2, '同级', '同级', 0);


                }

                if ($this->r) {
                    if ($this->order->is_platform) {
                        $this->saveCommission($this->r->id, $diff - $same, 1, '差价', '差价', 0);
                    } else {
                        $this->money += $same;
                    }
                }

            }

        }



        // var_dump(1111);exit;


    }

    // 不存在高级时, 找一个假设的高级
    protected function getX($value)
    {
        if ($value == UserLevel::$keys['none']) {
            // return UserLevel::$keys['vip1'];
            return UserLevel::$keys['vip2'];
        } else if ($value == UserLevel::$keys['vip1']) {
            return UserLevel::$keys['vip1'] + 1;
        }  else if ($value == UserLevel::$keys['vip2']) {
            return UserLevel::$keys['vip2'] + 1;
        }  else if ($value == UserLevel::$keys['vip3']) {
            return UserLevel::$keys['svip1'];
        }  else if ($value == UserLevel::$keys['svip1']) {
            return UserLevel::$keys['svip2'];
        }  else if ($value == UserLevel::$keys['svip2']) {
            return UserLevel::$keys['svip2'];
        }

        return 0;
    }


    // 临时等级
    protected function tempLevel()
    {
        $amount = $this->order->total_pay - $this->order->total_freight;

        if ($amount >= $this->set->svip1_amount) {
            // 经销商
            return UserLevel::$keys['svip1'];
        } else if ($amount >= $this->set->vip3_amount) {
            // VIP
            return UserLevel::$keys['vip3'];
        } else if ($amount >= $this->set->vip2_amount) {
            // 顾客
            return UserLevel::$keys['vip2'];
        } else if ($amount >= $this->set->vip1_price) {
            // 会员[零售]
            return UserLevel::$keys['vip1'];
        }

        return UserLevel::$keys['none'];
    }

    // 上级卖货(钱给上级)
    public function leaderMoney()
    {
        if ($this->order->leader == 0) {
            return;
        }

        // 扣除
        $money = $this->order->total_pay - $this->order->total_freight;
        $money -= $this->money;

        // $this->saveCommission($this->order->leader, $money, 33, '出货', '出货', 1);

        // 也改成待返
        $this->saveCommission($this->order->leader, $money, 33, '出货', '出货', 0);
    }

    // 找上级(链), 并且高于 购买者等级的用户
    protected function getRealReferrer($level)
    {
        $chain = Chain::getReferrerChain($this->user->id, [], true);

        foreach ($chain as $item) {

            // 找出第 1 个等级高的
            if ($item['level'] > $level) {

                $this->r = $item;

                return $item;
            }
        }

        return null;
    }

    // 处理是平台走, 还是上级走
    // [直推, 仓库够, 从上级走, 否则从平台走]
    private function exeBox()
    {
        // 这里要大于购买后台的等级 [复购用现在的等级]
        // $level = $this->user_level;
        if ($this->isRepeat) {
            $level = $this->user_level;
        } else {
            $level = $this->tempLevel();
        }

        // var_dump($level);exit;

        // 经销商, 区代, 直推从平台走
        if ($level >= UserLevel::$keys['svip1']) {
            return;
        }


        // $r = Chain::getReferrer($this->user->id, true);
        $r = $this->getRealReferrer($level);

        // var_dump($r);exit;

        if ($r && $r->level > $level) {
            // 云仓数量足够
            $r_store = UserStore::find()
                ->where(['user_id' => $r['id']])
                ->one();
            $box = $this->getBox();
            if (!$r_store || $r_store->num < $box) {

                // 从平台走, 库存预警
                $r->store_warn = 1;
                $r->save();

            } else {

                // 指定出货上级 [收钱]
                $this->order->leader = $r['id'];

                // 从上级走
                $this->order->is_platform = 0;
                $this->order->save();

                // 减少上级云仓
                if ($this->change_store) {
                    UserStoreLog::addLog($r_store->user_id, $r_store->num, -$box, $r_store->num - $box,
                        '出货', 2, $this->order->id);
                    $r_store->num -= $box;
                    $r_store->save();
                }
            }


        }

        // $log = $this->order->log;
        // if ($log) {
        //     $log = json_decode($log, true);
        //     $chain = $log['chain'];
        //     if ($chain) {
        //
        //         foreach ($chain as $user) {
        //             // 等级必须大于下单人, 必须是顾客+
        //             if ($user['level'] > $this->user_level && $user['level'] >= UserLevel::$keys['vip2']) {
        //                 // var_dump($user['id'], $this->user_level);exit;
        //
        //                 // 云仓数量足够
        //                 $user_store = UserStore::find()
        //                     ->where(['user_id' => $user['id']])
        //                     ->one();
        //                 $box = $this->getBox();
        //                 if (!$user_store || $user_store->num < $box) {
        //
        //                     // 从平台走, 库存预警
        //                     $u = User::findOne(['id' => $user['id']]);
        //                     $u->store_warn = 1;
        //                     $u->save();
        //
        //                 } else {
        //
        //                     // 从上级走
        //                     $this->order->is_platform = 0;
        //                     $this->order->save();
        //
        //                     // 减少上级云仓
        //                     UserStoreLog::addLog($user_store->user_id, $user_store->num, -$box, $user_store->num - $box, '出货', $this->order->id);
        //                     $user_store->num -= $box;
        //                     $user_store->save();
        //
        //                     // // 钱给上级
        //                     // $this->saveCommission($user['id'], $this->order->total_pay - $this->order->total_freight,
        //                     //     33, '出货', '出货', 1);
        //                 }
        //
        //                 // 只找一个(上级领导, 差价给他, 同级奖要从他差价中扣)
        //                 $this->order->leader = $user['id'];
        //                 $this->order->save();
        //                 break;
        //             }
        //         }
        //     }
        // }


    }

    // 折扣奖
    public function diff($sub = 0)
    {
        // if ($this->order->leader == 0) {
        //     return;
        // }
        //
        // $u = User::findOne(['id' => $this->order->leader]);
        //
        // // 货从平台出, 才返差价折扣奖
        // if ($u && $this->order->is_platform == 1) {
        //     $leader = UserLevel::getKey($u->level);
        //     $buy = UserLevel::getKey($this->user_level);
        //
        //     // 注意, 首购没复购折扣的, 所以首购差价不是根据等级来的
        //     // var_dump($this->_diff($leader), $this->_diff($buy));exit;
        //
        //     $diff = $this->_diff($leader) - $this->_diff($buy);
        //     // var_dump($diff, $sub);exit;
        //
        //     $this->saveCommission($u['id'], $diff - $sub, 1, '折扣');
        // }

        // 货从平台出, 才返差价折扣奖
        if ($this->order->is_platform == 1) {
            $this->repeatDiff();
        }
    }

    // 获取不同等级差价
    private function _diff($diff_key)
    {
        if ($diff_key == 'none') {
            $diff_key = 'vip1';
        }

        $sum = 0;
        foreach ($this->items as $item) {
            $product = Product::findOne(['id' => $item['product_id']]);
            $set_product = SetProductCommission::findOne(['product_id' => $item['product_id']])->toArray();

            // $sum += ($set_product['vip1'] - $set_product[$diff_key]) * $product['store'] *  $item['quantity'];

            // var_dump($diff_key, $set_product[$diff_key]);exit;

            $sum += ($set_product[$diff_key]) * $product['store'] *  $item['quantity'];
        }
        return $sum;
    }

    // 复购差价折扣, [复购都从平台走货]
    private function repeatDiff()
    {
        // 等级必须大于用户购买后的等级
        $level = $this->user_level;
        $level = $this->tempLevel();
        // var_dump($level);exit;

        $r = Chain::getReferrer($this->user->id, true);
        if ($r && $r->level > $level) {
            $buy = UserLevel::getKey($this->user_level);
            $referrer = UserLevel::getKey($r->level);

            $buy_price = $this->_diff($buy);
            $referrer_price = $this->_diff($referrer);

            // var_dump($buy_price, $referrer_price);exit;

            $this->saveCommission($r['id'], $referrer_price - $buy_price, 1, '差价');
        }

    }

    // 同级奖
    private function same()
    {
        $commission = 0;
        $r = Chain::getReferrer($this->user->id, true);
        // 必须是同级
        $level = $this->tempLevel();
        // var_dump($r->level, $level);exit;
        if ($r && $r->level == $level) {
            $amount = $this->order->total_pay - $this->order->total_freight;

            if ($amount >= $this->set->svip1_amount) {
                // 经销商
                $commission = $this->set->svip1_same;
            } else if ($amount >= $this->set->vip3_amount) {
                // VIP
                $commission = $this->set->vip3_same;
            } else if ($amount >= $this->set->vip2_amount) {
                // 顾客
                $commission = $this->set->vip2_same;
            }

            $this->saveCommission($r['id'], $commission, 2, '同级直推');
        }

        return $commission;
    }
    
    // 经销商 推 经销商 复购
    // v4, 经销商, 区代都可以了, 低推高没有
    private function repeatSvip1()
    {
        if (!in_array($this->user_level, [UserLevel::$keys['svip1'], UserLevel::$keys['svip2']])) {
            return;
        }

        // $r = User::find()
        //     ->where(['id' => $this->user->referrer_id])
        //     ->andWhere(['level' => [UserLevel::$keys['svip1'], UserLevel::$keys['svip2']]])
        //     ->one();
        //
        // // 低推高没有
        // if ($r && $r->level >= $this->user_level) {
        //
        //     $total_pay = $this->order->total_pay - $this->order->total_freight;
        //
        //     $commission = $this->set->svip1_repeat / 100 * $total_pay ;
        //
        //     $this->saveCommission($r['id'], $commission, 66, '经销商复购');
        // }


        $chain = Chain::getReferrerChain($this->user->id, [UserLevel::$keys['svip1'], UserLevel::$keys['svip2']], true);
        $total_pay = $this->order->total_pay - $this->order->total_freight;
        $commission = $this->set->svip1_repeat / 100 * $total_pay ;


        // 如果有 区代 了
        // todo 如果不截断, 就判断 $has_svip2 的判断
        $has_svip2 = false;

        foreach ($chain as $r) {
            if ($this->user_level == UserLevel::$keys['svip2'] && $r->level == UserLevel::$keys['svip1']) {
                continue;
            }

            if ($r->level == UserLevel::$keys['svip2']) {
                $has_svip2 = true;
            }
            if ($has_svip2 && $r->level == UserLevel::$keys['svip1']) {
                continue;
            }

            $this->saveCommission($r['id'], $commission, 66, '经销商复购');
        }
    }

    // 地区奖
    public function area()
    {
        // 没有地址, 云仓也有地址, 才有奖
        if ($this->order->user_address == 0) {
            return;
        }

        $address = UserAddress::find()
            ->where(['id' => $this->order->user_address])
            ->andWhere(['user_id' => $this->user->id])
            ->one();

        if ($address) {
            $province_id = $address->province_id;
            $city_id = $address->city_id;
            $area_id = $address->area_id;

            $users = User::find()
                ->where(['level' => UserLevel::$keys['svip2']])
                // 把区放最前面, 可能只返1个人
                ->andWhere(['address_up' => [$area_id, $city_id, $province_id]])
                ->andWhere(['>', 'address_up', 0])
                // 只返1个, 以后允许市和省, 就可以不限制了
                ->limit(1)
                ->all();

            // var_dump($users);exit;

            // 如果是提货的, 则不用计算
            if ($this->order->is_extract) {
                $box = $this->order->is_extract;
            } else {
                $box = $this->getBox();
            }

            foreach ($users as $user) {
                $commission = $this->set->svip2_repeat * $box;

                // 公司出钱
                // $this->money += $commission;

                $this->saveCommission($user['id'], $commission, 77, '区域奖');
            }
        }
    }

    // 分红, 每单拿30元
    public function profit()
    {
        $log = $this->order->log;
        if (!$log) {
            return;
        }

        $log = json_decode($log, true);
        $chain = $log['chain'];
        if ($chain) {
            // 找出第1个区域
            foreach ($chain as $user) {
                if ($user['level'] == UserLevel::$keys['svip2']) {

                    // 1) 必须直推3个区代
                    $count = User::find()
                        ->where(['referrer_id' => $user['id']])
                        ->andWhere(['level' => UserLevel::$keys['svip2']])
                        ->count();

                    // var_dump($count, $this->set->address_num);exit;

                    if (intval($count) >= $this->set->address_num) {

                        // var_dump($user['id']);exit;

                        // 2) 业绩部门中不能有超过50%的
                        if (!$this->isOut($user['id'])) {

                            $this->_profit($user);

                        }

                        // 如果是一个一个找
                        // break;
                    }

                    // 只处理团队中第1个
                    break;
                }
            }
        }
    }

    // 计算是否有超过50%的
    private function isOut($user_id)
    {
        $total_ids = Chain::getChildrenAllQuick($user_id, [], ['id']);
        $total_ids = ArrayHelper::getColumn($total_ids, 'id');
        $total_ids = array_merge([$user_id], $total_ids);

        $child_svip2 = User::find()
            ->where(['referrer_id' => $user_id])
            ->andWhere(['level' => UserLevel::$keys['svip2']])
            ->select(['id'])
            ->column();

        // var_dump($total_ids, $child_svip2);exit;

        // 总业绩
        $total_box = $this->boxByOrder($total_ids);
        if ($total_box == 0) {
            return false;
        }

        // var_dump($total_box);exit;

        // 判断部门业绩
        foreach ($child_svip2 as $id) {
            $child = Chain::getChildrenAllQuick($id, [], ['id']);
            $child = ArrayHelper::getColumn($child, 'id');
            $child = array_merge([$id], $child);
            $box = $this->boxByOrder($child);

            // echo $box, ' - ';
            // continue;

            // 是否大于50%
            if ($box / $total_box >= 0.5) {
                return true;
            }
        }

        // exit;

        return false;
    }

    // 根据全部订单ids, 计算盒数
    private function boxByOrder($ids)
    {
        $orders = Order::find()
            ->where(['user_id' => $ids])
            ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
            ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
            ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
            ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
            // 提货的不算
            ->andWhere(['is_extract' => 0])
            ->select(['id'])
            ->column();

        $items = OrderItem::find()
            ->where(['order_id' =>$orders])
            ->with(['product'])
            ->all();
        $box = 0;
        foreach ($items as $item) {
            if ($item['product']) {

                // 84000 不算
                if ($item['product']['price'] == 84000) {
                    continue;
                }

                $box += $item['product']['store'] * $item['quantity'];
            }
        }

        return  $box;
    }

    private function _profit($user)
    {
        $u = User::findOne(['id' => $user['id']]);
        if ($u) {
            $box = $this->getBox();
            // 如果按订单算, 则把盒数改成1
            // $box = 1;

            // var_dump($box);exit;

            $commission = $this->set->address_award * $box;

            // 公司出钱
            // $this->money += $commission;

            $this->saveCommission($u['id'], $commission, 88, '分红');
        }

    }

    // 累计业绩奖
    public function sell()
    {
        // 如果是重算佣金, 则不处理
        // if (!$this->change_store) {
        //     return;
        // }

        $log = $this->order->log;
        if (!$log) {
            return;
        }

        $log = json_decode($log, true);
        $chain = $log['chain'];

        // var_dump($chain);exit;

        if ($chain) {
            foreach ($chain as $user) {
                if ($user['level'] == UserLevel::$keys['svip1'] || $user['level'] == UserLevel::$keys['svip2']) {
                    $this->_sell($user);
                }
            }
        }
    }

    private function _sell($user)
    {
        // 直推多少个经销商+
        $children = User::find()
            ->where(['referrer_id' => $user['id']])
            ->andWhere(['level' => [
                UserLevel::$keys['svip1'],
                UserLevel::$keys['svip2']
            ]])
            ->select(['id'])
            ->column();

        // 小于4个, 则不返
        if (count($children) < $this->set->box_num) {
            return;
        } else {
            // debug
            // var_dump($user['id']);
        }

        $total_ids = Chain::getChildrenAllQuick($user['id'], [], ['id']);
        $total_ids = ArrayHelper::getColumn($total_ids, 'id');
        $total_ids = array_merge([$user['id']], $total_ids);

        // 本人总业绩
        $total = $this->boxByOrder($total_ids);
        // var_dump($total);exit;

        foreach ($children as $id) {
            $child = Chain::getChildrenAllQuick($id, [], ['id']);
            $child = ArrayHelper::getColumn($child, 'id');
            $child = array_merge([$id], $child);
            $box = $this->boxByOrder($child);

            if ($total == 0) {
                return;
            }

            if ($box / $total >= 0.5) {
                // 减掉
                $total -= $box;
            }
        }

        // var_dump($total);exit;
        $amount = 0;
        $amount1 = $this->set->box1_award * $this->set->box1;
        $amount2 = $this->set->box2_award * $this->set->box2;
        $amount3 = $this->set->box3_award * $this->set->box3;
        $amount4 = $this->set->box4_award * $this->set->box4;
        $u = User::findOne(['id' => $user['id']]);
        if ($total >= $this->set->box1 && $u->sell_1 == 0) {
            $u->sell_1 = $this->order->id;
            $amount = $amount1;
        } else if ($total >= $this->set->box2 && $u->sell_2 == 0) {
            $u->sell_2 = $this->order->id;
            $amount = $amount2 - $amount1;
        } else if ($total >= $this->set->box3 && $u->sell_3 == 0) {
            $u->sell_3 = $this->order->id;
            $amount = $amount3 - $amount2 - $amount1;
        } else if ($total >= $this->set->box4 && $u->sell_4 == 0) {
            $u->sell_4 = $this->order->id;
            $amount = $amount4 - $amount3 - $amount2 - $amount1;
        }

        // var_dump($amount, $total);exit;

        if ($amount > 0) {
            $u->save();

            // 已返
            $this->saveCommission($u['id'], $amount, 101, '业绩奖', '业绩完成', 1);
        }

    }


    // 获取订单盒数
    protected function getBox()
    {
        // 如果订单有保存盒数, 则从订单从来
        if ($this->order->is_store == 1 && $this->order->store_box > 0) {
            return $this->order->store_box;
        }

        // 否则从产品中算 (可能产品有改动)
        $items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->with(['product'])
            ->all();
        $box = 0;
        foreach ($items as $item) {
            if ($item['product']) {
                $box += $item['product']['store'] * $item['quantity'];
            }
        }

        return  $box;
    }

    // 保存佣金 (await balance)
    protected function saveCommission($user_id, $balance, $type, $name, $text = '返佣', $status = 0)
    {
        if ($balance >= 0.01) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $this->order->user_id;
            $model->order_id = $this->order->id;
            $model->balance = $balance;
            $model->status = $status;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();

            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {
                if ($status == 1) {
                    $account->balance += $balance;
                } else {
                    $account->await_balance += $balance;
                }
                $account->save();
            }

            // balance logs
            if ($status == 1) {
                UserBalance::addLog($model->user_id,
                    $account->balance, $model->balance, $account->balance + $model->balance, $text, $this->order->id);
            }
        }
    }
}